package com.qian.service.ddj.serviceImpl;

import com.qian.api.ddj.model.Spider;
import com.qian.api.ddj.model.SpiderCount;
import com.qian.api.ddj.model.SpiderQueryModel;
import com.qian.api.ddj.service.ISpiderService;
import com.qian.service.ddj.dao.BusinessRepository;
import com.qian.service.ddj.dao.SpiderRepositody;
import com.qian.service.ddj.entity.DdjSpider;
import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import com.yaowk.service.common.BaseRepository;
import com.yaowk.service.common.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.util.*;

@Service
public class SpiderServiceImpl extends BaseServiceImpl<Spider,DdjSpider,Integer> implements ISpiderService {
    @Autowired
    private SpiderRepositody dao;
    @Autowired
    private BusinessRepository businessDao;

    @Override
    public Spider save(Spider spider){
        if (spider.isNew()){
            spider = simpleSave(spider);
        }else{
            DdjSpider ddjSpider = dao.findOne(spider.getId());
            if (isNotEmpty(spider.getAmount())){
                ddjSpider.setAmount(spider.getAmount());
            }
            if (isNotEmpty(spider.getName())){
                ddjSpider.setName(spider.getName());
            }
            if (isNotEmpty(spider.getOrderInfo())){
                ddjSpider.setOrderInfo(spider.getOrderInfo());
            }
            if (isNotEmpty(spider.getPayDate())){
                ddjSpider.setPayDate(spider.getPayDate());
            }
            if (isNotEmpty(spider.getRemark())){
                ddjSpider.setRemark(spider.getRemark());
            }
            if (isNotEmpty(spider.getStatus())){
                ddjSpider.setStatus(spider.getStatus());
            }
            spider = entity2model(dao.save(ddjSpider));
        }
        return spider;
    }

    @Override
    protected BaseRepository getDao() {
        return dao;
    }

    @Override
    protected DdjSpider model2Entity(Spider model) {
        DdjSpider ddjSpider = null;
        if (isNotEmpty(model)){
            ddjSpider = new DdjSpider();
            ddjSpider.setAmount(model.getAmount());
            ddjSpider.setName(model.getName());
            ddjSpider.setOrderInfo(model.getOrderInfo());
            ddjSpider.setPayDate(model.getPayDate());
            ddjSpider.setRemark(model.getRemark());
            ddjSpider.setStatus(model.getStatus());
            ddjSpider.setId(model.getId());
            ddjSpider.setBusinessId(model.getBusinessId());
        }
        return ddjSpider;
    }

    @Override
    protected Spider entity2model(DdjSpider entity) {
        Spider spider = null;
        if (isNotEmpty(entity)){
            spider = new Spider();
            spider.setAmount(entity.getAmount());
            spider.setName(entity.getName());
            spider.setOrderInfo(entity.getOrderInfo());
            spider.setPayDate(entity.getPayDate());
            spider.setRemark(entity.getRemark());
            spider.setStatus(entity.getStatus());
            spider.setId(entity.getId());
            spider.setBusinessId(entity.getBusinessId());
        }
        return spider;
    }

    @Override
    public Spider findFirstByBusinessId(Integer businessId) {
        PageRequest pageRequest = new PageRequest(0, 1, Sort.Direction.DESC, "id");
        DdjSpider ddjSpider = new DdjSpider();
        ddjSpider.setBusinessId(businessId);
        Page<DdjSpider> page = dao.findAll(Example.of(ddjSpider), pageRequest);
        List<DdjSpider> spiderList = page.getContent();
        if (CollectionUtils.isEmpty(spiderList)) {
            return null;
        }

        return entity2model(spiderList.get(0));
    }

    @Override
    public List<SpiderCount> count(final SpiderQueryModel model) {

        List<DdjSpider> spiders = dao.findAll(new Specification<DdjSpider>() {
            @Override
            public Predicate toPredicate(Root<DdjSpider> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate condition = criteriaBuilder.isNotNull(root.<Integer>get("id"));
                Path<Date> timePath = root.get("payDate");
                // 日期比较
                if (isNotEmpty(model.getBeginTime()) && isNotEmpty(model.getEndTime()))
                    condition = criteriaBuilder.and(condition, criteriaBuilder.between(timePath, model.getBeginTime(), model.getEndTime()));
                else if (isNotEmpty(model.getBeginTime()))
                    condition = criteriaBuilder.and(condition, criteriaBuilder.greaterThanOrEqualTo(timePath, model.getBeginTime()));
                else if (isNotEmpty(model.getEndTime()))
                    condition = criteriaBuilder.and(condition, criteriaBuilder.lessThanOrEqualTo(timePath, model.getEndTime()));
                return condition;
            }
        });

        Map<Integer, SpiderCount> map = new HashMap<>();
        for (DdjSpider spider : spiders) {
            String[] amounts = spider.getAmount().split(" ");
            if (amounts.length == 2 && amounts[0].equalsIgnoreCase("+") && "交易成功".equalsIgnoreCase(spider.getStatus())) {
                SpiderCount spiderCount = map.getOrDefault(spider.getBusinessId(), new SpiderCount(new BigDecimal(0), businessDao.findOne(spider.getBusinessId()).getAccount()));
                map.put(spider.getBusinessId(), spiderCount);
                spiderCount.setTotal(spiderCount.getTotal().add(new BigDecimal(amounts[1])));
            }
        }

        List<SpiderCount> result = new ArrayList<>();
        for (Map.Entry<Integer, SpiderCount> entry : map.entrySet()) {
            result.add(entry.getValue());
        }

        return result;
    }

    @Override
    public PageResp<Spider> findAll(SpiderQueryModel model, PageReq pageReq) {
        DdjSpider ddjSpider = new DdjSpider();
        if (isNotEmpty(model.getOrderInfo()))
            ddjSpider.setOrderInfo("%" + model.getOrderInfo() + "%");
        if (isNotEmpty(model.getRemark()))
            ddjSpider.setRemark("%" + model.getRemark() + "%");
        return null;
    }

    @Override
    public List<Spider> findAll(Spider model) {
        List<DdjSpider> result = dao.findAll(new Specification<DdjSpider>() {
            @Override
            public Predicate toPredicate(Root<DdjSpider> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate condition = criteriaBuilder.isNotNull(root.<Integer>get("id"));
                if (StringUtils.isNotBlank(model.getRemark())) {
                    condition = criteriaBuilder.and(condition, criteriaBuilder.equal(root.get("remark"), model.getRemark()));
                }
                if (StringUtils.isNotBlank(model.getOrderInfo())) {
                    condition = criteriaBuilder.and(condition, criteriaBuilder.like(root.get("orderInfo"), "%" + model.getOrderInfo() + "%"));
                }

                return condition;
            }
        });
        return entity2Model(result);
    }
}
